import time
import urllib
from urllib.parse import urlparse, parse_qs, quote_plus
from DrissionPage import Chromium,ChromiumOptions
from DrissionPage._elements.none_element import NoneElement
from urllib.parse import urlparse, parse_qs
import json
from config import redis_config
from cookie import cookie_to_dict
from redis_api import get_redis
redis = get_redis(redis_config)
#邮箱密码
mail = 'beginvpnchannel@gmail.com'
password = 'dEbUg2024@@@'
co= ChromiumOptions()
tab = Chromium(addr_or_opts=co).latest_tab
def get_url_params(url):
    # 解析 URL
    parsed_url = urlparse(url)

    # 获取查询参数并转换为字典
    params_dict = parse_qs(parsed_url.query)

    # 将值转换为字符串（去掉列表）
    params_dict = {k: v[0] for k, v in params_dict.items()}

    return params_dict
def parse_cookies(cookie_string):
    cookies = []
    for cookie in cookie_string.split('; '):
        name, value = cookie.split('=', 1)
        # 每个 cookie 需要 domain 和 path
        cookies.append({
            'name': name,
            'value': urllib.parse.quote(value),
            'domain': 'www.booking.com',  # 确保设置正确的域名
            'path': '/',       # 通常设置为根路径
        })
    return cookies

def get_holtel_info(checkin,checkout,lang,dest_id,dest_type,pageName,countryCode):
    import requests
    url = F"http://127.0.0.1:5000/api/user/hotel?checkin={checkin}&checkout={checkout}&lang={lang}&mail={mail}&dest_id={dest_id}&dest_type={dest_type}&pageName={pageName}&countryCode={countryCode}"
    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    return json.loads(response.text)
# 设置代理

# 设置 cookies
application_data = redis.get(f'application_data_{mail}')
application_data = json.loads(application_data)
base_page_url_dict = get_url_params(application_data['basePageUrl'])
label = application_data['affiliate']['label']
key = application_data['affiliate']['label']
sid = base_page_url_dict['sid']
aid = base_page_url_dict['aid']
cookie_string = redis.get(f'cookie_str_{mail}')
cookie_string = str(cookie_string,'utf-8')
cookies = parse_cookies(cookie_string)


checkin='2024-10-28'
checkout='2024-10-31'
lang='en-gb'
dest_id='-1456928'
dest_type='city'
pageName='best-western-sydney-opera-paris1'
countryCode='fr'
# holtel_info = get_holtel_info(checkin,checkout,lang,dest_id,dest_type,pageName,countryCode)
# room_data =holtel_info['data']['room_data']
# #过滤不符合的房间
# room_data = [item for item in room_data if 'pay at the property' in item['room_conditions']]
# #默认第1家
# room_block_id = room_data[0]['room_block_id']
# destination_dict = holtel_info['data']['destination_dict']
# hotel_id = destination_dict['hotel_id']
# nflt = quote_plus(destination_dict['nflt'])
# room1 = quote_plus(destination_dict['room1'])
# hostname = 'www.booking.com'
# stage = destination_dict['stage']
# checkin = destination_dict['checkin']
# interval = destination_dict['interval']
# srpvid = destination_dict['srpvid']
# rt_pos_selected = destination_dict['rt_pos_selected']
# rt_pos_selected_within_room = destination_dict['rt_pos_selected_within_room']
# rt_selected_block_position = destination_dict['rt_selected_block_position']
# rt_num_blocks = destination_dict['rt_num_blocks']
# rt_num_rooms = destination_dict['rt_num_rooms']
# rt_num_blocks_per_room = quote_plus(destination_dict['rt_num_blocks_per_room'])
# rt_selected_blocks_info = quote_plus(destination_dict['rt_selected_blocks_info'])
# rt_relevance_metric_id = destination_dict['rt_relevance_metric_id']
# rt_pageview_id = destination_dict['rt_pageview_id']
# rt_pos_final = destination_dict['rt_pos_final']
# rt_selected_total_price = destination_dict['rt_selected_total_price']
# rt_cheapest_search_price = destination_dict['rt_cheapest_search_price']
# error_url = quote_plus(F'/hotel/{countryCode}/{pageName}.{lang}.html?aid={aid}&label={label}&sid={sid}&srpvid={srpvid}')
# basket_id = destination_dict['basket_id']
# 以该配置创建页面对象
#target_url = f'https://secure.booking.com/book.html?nflt={nflt}&hotel_id={hotel_id}&aid={aid}&label={label}&lang={lang}&sid={sid}&room1={room1}&error_url={error_url}&hostname={hostname}&stage={stage}&checkin={checkin}&interval={interval}&children_extrabeds=&srpvid={srpvid}&hp_visits_num=1&rt_pos_selected={rt_pos_selected}&rt_pos_selected_within_room={rt_pos_selected_within_room}&rt_selected_block_position={rt_selected_block_position}&rt_num_blocks={rt_num_blocks}&rt_num_rooms={rt_num_rooms}&rt_num_blocks_per_room={rt_num_blocks_per_room}&rt_selected_blocks_info={rt_selected_blocks_info}&rt_relevance_metric_id={rt_relevance_metric_id}&rt_pageview_id={rt_pageview_id}&rt_pos_final={rt_pos_final}&rt_selected_total_price={rt_selected_total_price}&rt_cheapest_search_price={rt_cheapest_search_price}&rt_with_no_dimensions=&from_source=hotel&basket_id={basket_id}&nr_rooms_{room_block_id}=1'
#old_target_url = 'https://secure.booking.com/book.html?nflt=fc%3D2&hotel_id=1549960&aid=304142&label=gen173bo-1FCAEoggI46AdICVgDaFCIAQGYAQm4ARjIAQzYAQHoAQH4AQSIAgGYAgKoAgS4AtyzrrgGwAIB0gIkYzQ0Zjg0ZDctOGJjYS00NDRlLWI0NjgtZWI1ODY4MGQ5Y2M12AIF4AIB&lang=en-gb&sid=d780c8b2870cb292996113ccc35caf96&room1=A%2CA&error_url=%2Fhotel%2Ffr%2Fhotelf1-paris-porte-de-chatillon-paris.en-gb.html%3Faid%3D304142%26label%3Dgen173bo-1FCAEoggI46AdICVgDaFCIAQGYAQm4ARjIAQzYAQHoAQH4AQSIAgGYAgKoAgS4AtyzrrgGwAIB0gIkYzQ0Zjg0ZDctOGJjYS00NDRlLWI0NjgtZWI1ODY4MGQ5Y2M12AIF4AIB%26sid%3Dd780c8b2870cb292996113ccc35caf96%26srpvid%3D1585463243da0047%26%26&hostname=www.booking.com&stage=1&checkin=2024-10-21&interval=2&children_extrabeds=&srpvid=1585463243da0047&hp_visits_num=1&rt_pos_selected=1&rt_pos_selected_within_room=1&rt_selected_block_position=1&rt_num_blocks=18&rt_num_rooms=3&rt_num_blocks_per_room=%7B%22154996008%22%3A6%2C%22154996009%22%3A6%2C%22154996007%22%3A6%7D&rt_selected_blocks_info=%7B%22154996007_376292959_2_2_0%22%3A%7B%22rt_selected_block_position_in_rt%22%3A1%2C%22rt_selected_block_position_in_room_group%22%3A0%2C%22count%22%3A1%2C%22rt_room_symmetry_category%22%3A%22asymmetric%22%7D%7D&rt_relevance_metric_id=fc2f7495-300b-40ac-9e47-b2d76caa4d5c&rt_pageview_id=551f463f993c067d&rt_pos_final=1.1&rt_selected_total_price=228&rt_cheapest_search_price=206&rt_with_no_dimensions=&from_source=hotel&basket_id=99dfc5e2-9569-4c2a-9788-0135fa11599e&nr_rooms_154996007_376292959_2_2_0=1'
# 导航到你想打印的网页
target_url = f'https://www.booking.com/hotel/{countryCode}/{pageName}.{lang}.html?aid={aid}&label={label}&sid={sid}&age=1&checkin={checkin}&checkout={checkout}&dest_id={dest_id}&dest_type={dest_type}&dist=0&do_availability_check=1&group_adults=2&group_children=1&hp_avform=1&hp_group_set=0&no_rooms=1&origin=hp&sb_price_type=total&src=hotel&type=total&#group_recommendation'
print(target_url)

tab.get(target_url)

select_al = tab.ele('css=input[name="selectAll"]')
if isinstance(select_al, NoneElement):
    print("元素不存在 (NoneElement)")
else:
    time.sleep(1)
    tab.run_js("document.querySelector('input[name=\"selectAll\"]').click()")
    time.sleep(1)
    tab.wait.ele_displayed('button')
    tab.ele('button').click()

sign_in_el = tab.ele('css=a[data-testid="header-sign-in-button"]')
# 判断是否登录
if isinstance(sign_in_el, NoneElement):
    print("登录成功")
else:
    # 登录页面
    sign_in_el = 'css=a[data-testid="header-sign-in-button"]'
    tab.wait.ele_displayed(sign_in_el)
    tab.ele(sign_in_el).click()
    # 勾选协议
    r3_el = tab.ele('#:r3:')
    if isinstance(r3_el, NoneElement):
        print("元素不存在 (NoneElement)")
    else:
        tab.ele('#:r3:').click()
        time.sleep(1)
    # 输入账号
    tab.wait.ele_displayed('#username')
    tab.ele('#username').clear()
    tab.ele('#username').input(mail)
    # 提交邮箱
    time.sleep(0.2)
    tab.ele('css=button[type="submit"]').click()
    # # 定位到密码文本框并输入密码
    tab.wait.load_start()
    tab.wait.ele_displayed('css=input[type="password"]')
    tab.ele('css=input[type="password"]').clear()
    tab.ele('css=input[type="password"]').input(password)
    # 点击登录按钮
    tab.ele('css=.nw-signin button[type="submit"]').click()
#等待跳转结束
tab.wait.doc_loaded()
room_data = []
room_trs = tab.eles('css=#hprt-table tbody tr')
room_name = ''
room_info = ''
option = None
for room_tr in room_trs:
    room_name_el =  room_tr.ele('css=div[data-et-mouseenter="goal:hp_rt_hovering_room_name"] .hprt-roomtype-icon-link')
    room_info_el = room_tr.ele('css=.-first')
    if isinstance(room_name_el, NoneElement):
        print("跨度")
    else:
        room_name = room_name_el.text

    if isinstance(room_info_el, NoneElement):
        print("跨度")
    else:
        # 只在当前 room_tr 上查找 room_info
        room_info = room_info_el.text  # 注意加上 '.' 表示从当前节点查找

    room_occupancy = room_tr.ele('css=.hprt-table-cell-occupancy .bui-u-sr-only').text

    room_block_id = room_tr.attr('data-block-id')
    room_price = room_tr.attr('data-hotel-rounded-price')

    # 修正 XPath 为相对路径
    room_conditions = room_tr.ele('css=.hprt-table-cell-conditions').text  # 这里也加上 '.'

    if 'pay at the property' in room_conditions:
        #选一个可以的预定
        option = room_tr.eles('@tag()=option')
        option = option[1]
        break
    room_data.append({
        "room_name": room_name,
        "room_info": room_info,
        "room_occupancy": room_occupancy,
        "room_block_id": room_block_id,
        "room_price": room_price,
        "room_conditions": room_conditions
    })
if option is not None:
    option.click()
    reservation_button = tab.ele('css=.js-reservation-button')
    reservation_button.click()

    tab.wait.doc_loaded()
    tab.wait.ele_displayed('#notstayer_true')
    tab.ele('#notstayer_true').click()

    tab.wait.ele_displayed('css=.js-bp-submit-button--next-step')
    tab.ele('css=.js-bp-submit-button--next-step').click()

    #支付信息页面

    tab.wait.ele_displayed('css=.cc_cvc_input')
    tab.ele('css=.cc_cvc_input').input('539')

    tab.wait.ele_displayed('#privacy_consent_china_pipl')
    tab.ele('#privacy_consent_china_pipl').click()

    #完成
    tab.wait.ele_displayed('css=.js-bp-submit-button--complete-booking')
    tab.ele('css=.js-bp-submit-button--complete-booking').click()


print()